import json
import os
import psutil
import time

CPU_PERCENT_INTERVAL = 1
CAPTURE_INTERVAL = 5
DB_FILENAME = 'stat.txt'


def get_current_s():
    return int(time.time())


def get_current_ms():
    return int(time.time() * 1000)


def get_system_stat():
    cpu = psutil.cpu_percent(interval=CPU_PERCENT_INTERVAL)
    memory = psutil.virtual_memory().percent
    load_avg = ",".join([str(float("%.2f" % x)) for x in os.getloadavg()])
    disk_usage = psutil.disk_usage('/').percent
    boot_ts = psutil.boot_time()
    net_status = {}
    for connection in psutil.net_connections('tcp'):
        net_status.setdefault(connection.status, 0)
        net_status[connection.status] += 1
    stat = dict(
        ts=get_current_ms(),
        cpu=cpu,
        memory=memory,
        load_avg=load_avg,
        disk_usage=disk_usage,
        boot_seconds=int(get_current_s() - boot_ts),
        network=net_status,
    )
    return stat


def main():
    while True:
        time.sleep(CAPTURE_INTERVAL)
        stat = get_system_stat()
        with open(DB_FILENAME, 'a') as f:
            stat = json.dumps(stat)
            f.write(stat + '\n')


if __name__ == '__main__':
    main()
